﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Skyhook.AI.Animators;
using Skyhook.AI.PathFinder;
using Skyhook.Core;
using Skyhook;

namespace Skyhook.AI.States.MovingEntity
{
    class MovingState : State
    {
        MovePathAnimator Animator = null;
        MovePath Path = null;

        IObjectController ObjectController = null;

        float Speed = 0.0f;
        Point Destination;

        bool IsAnimating = false;

        public MovingState(IObjectController controller)
            : base()
        {
            ObjectController = controller;

            Animator = new MovePathAnimator(ObjectController);
            Animator.OnFinish += OnAnimationFinish;
            
            IsFinished = false;
        }

        public override void Start()
        {
            CreatePathAndStartPathfinding();

            IsAnimating = false;
            IsFinished = false;
        }

        void CreatePathAndStartPathfinding()
        {
            Path = new MovePath();
            PathFinder.PathFinder.FindPathAsync((int)ObjectController.X, (int)ObjectController.Y, Destination.X, Destination.Y, Path);
        }

        public override void Update(float elapsedticks)
        {
            if (IsAnimating)
            {
                Animator.Update(elapsedticks);
            }
            else
            {
                if (Path.Completed)
                {
                    StartAnimation();
                }
            }
        }

        void StartAnimation()
        {
            Animator.Speed = Speed;
            Animator.Path = Path;

            Animator.StartAnimation();
            IsAnimating = true;
        }

        public override void Stop()
        {
            if (IsAnimating)
            {
                Animator.AbortAnimation();
            }
            else
            {
                IsFinished = true;
            }
        }

        void OnAnimationFinish()
        {
            IsFinished = true;
            IsAnimating = false;
        }

        public void SetDestination(int x, int y)
        {
            Destination = new Point(x, y);
        }

        public void SetSpeed(float speed)
        {
            Speed = speed;
        }
    }
}
